﻿using System;
using Common.Devices.Comm.Model;
using Tools.TcpSocket;

namespace Common.Devices.Comm
{
    /// <summary>
    /// tcp服务端 
    /// </summary>
    public class TcpServerHelper : ITransmission
    {
        /// <summary>
        /// tcp 服务
        /// </summary>
        private readonly TcpService _server;
        /// <summary>
        /// 客户端
        /// </summary>
        private IDataTransmit _client;

        /// <summary>
        /// 状态
        /// </summary>
        private bool _state;
        public TcpServerHelper() : this(8000)
        {
        }
        /// <summary>
        /// 构造方法
        /// </summary> 
        /// <param name="port"></param> 
        public TcpServerHelper(int port) : this(new TcpServerInfo() { Port = port })
        {
        }

        public TcpServerHelper(TcpServerInfo info)
        {
            Parameter = info;

            //在指定端口上建立监听线程
            _server = new TcpService(info.Port,info.Backlog, "0.0.0.0");
            //连接事件
            _server.Connected += (sender, e) =>
            {
                try
                {
                    _client = sender;
                    //接收数据
                    sender.ReceiveData += ReceiveData;
                    sender.Start();
                    //Log(sender.RemoteEndPoint + " 连接成功", null);
                }
                catch (Exception)
                {
                    //LogManager?.Error(ex);
                }
            };
            _server.DisConnect += (sender, e) =>
            {
                //Log(DateTime.Now.ToLongTimeString() + " " + sender.RemoteEndPoint + " 连接断开", null); 
            };
        }

        /// <summary>
        /// 接收消息 处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReceiveData(IDataTransmit sender, NetEventArgs e)
        {
            try
            {
                byte[] data = (byte[])e.EventArg;
                Received?.Invoke(data);
                // sender.Send(new byte[] { 0x1 });
            }
            catch (Exception)
            {
                // ignored
            }
        }
        public CommParameter Parameter { get; set; }
        public event Action<byte[]> Received;
        public bool Open()
        {
            try
            {


                _server.Start();
            }
            catch (Exception)
            {
                return false;
            }

            _state = true;
            return true;
        }
        public bool Close()
        {
            try
            {
                _server.Close();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        public bool IsOpen()
        {
            return _state;
        }
        public bool Send(byte[] buffer)
        {
            return _client.Send(buffer);
        }
    }
}
